import axios from 'axios';
import {clearToken} from "@/apis/config.ts";

const services = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000,
});

// 请求拦截器
services.interceptors.request.use(
    (config) => {
        // 在这里可以添加请求前的处理，比如添加token
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
services.interceptors.response.use(
    (response: any) => {
        const data = response.data;
        if (data.code === 401) {
            clearToken()
        }


        //   这里返回对应的拆包
        return data;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);
const request = Object.assign(
    (config: any) => {
        return services(config);
    },
    {
        get: (url: string, params?: any): Promise<any> => services.get(url, {params}),
        post: (url: string, data?: any, params?: any): Promise<any> => services.post(url, data, {params}),
        put: (url: string, data?: any, params?: any): Promise<any> => services.put(url, data, {params}),
        delete: (url: string, params?: any): Promise<any> => services.delete(url, {params})
    }
)
export default request